//! # 告警系统模块
//!
//! 提供智能告警、通知和告警规则管理功能

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// 为了向后兼容，创建类型别名
type ObservabilityResult<T> = Result<T, crate::ObservabilityError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_alert_manager() {
        let mut manager = AlertManager::new();
        manager.add_handler(Box::new(LogAlertHandler));
        
        let alert = Alert {
            id: "test-001".to_string(),
            level: AlertLevel::Warning,
            title: "测试告警".to_string(),
            message: "这是一个测试告警".to_string(),
            timestamp: chrono::Utc::now(),
            data: std::collections::HashMap::new(),
        };
        
        assert!(manager.process_alert(alert).await.is_ok());
    }
}

/// 告警级别
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlertLevel {
    Info,
    Warning,
    Error,
    Critical,
}

/// 告警信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Alert {
    pub id: String,
    pub level: AlertLevel,
    pub title: String,
    pub message: String,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub data: HashMap<String, serde_json::Value>,
}

/// 告警处理器接口
#[async_trait]
pub trait AlertHandler: Send + Sync {
    async fn send_alert(&self, alert: Alert) -> ObservabilityResult<()>;
}

/// 告警规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertRule {
    pub name: String,
    pub condition: String,
    pub level: AlertLevel,
    pub message_template: String,
}

/// 告警管理器
pub struct AlertManager {
    handlers: Vec<Box<dyn AlertHandler>>,
    rules: Vec<AlertRule>,
}

impl AlertManager {
    pub fn new() -> Self {
        Self {
            handlers: Vec::new(),
            rules: Vec::new(),
        }
    }

    pub fn add_handler(&mut self, handler: Box<dyn AlertHandler>) {
        self.handlers.push(handler);
    }

    pub fn add_rule(&mut self, rule: AlertRule) {
        self.rules.push(rule);
    }

    pub async fn process_alert(&self, alert: Alert) -> ObservabilityResult<()> {
        for handler in &self.handlers {
            if let Err(e) = handler.send_alert(alert.clone()).await {
                tracing::error!("告警处理失败: {}", e);
            }
        }
        Ok(())
    }
}

/// 日志告警处理器
pub struct LogAlertHandler;

#[async_trait]
impl AlertHandler for LogAlertHandler {
    async fn send_alert(&self, alert: Alert) -> ObservabilityResult<()> {
        match alert.level {
            AlertLevel::Critical | AlertLevel::Error => {
                tracing::error!("[ALERT] {}: {}", alert.title, alert.message);
            }
            AlertLevel::Warning => {
                tracing::warn!("[ALERT] {}: {}", alert.title, alert.message);
            }
            AlertLevel::Info => {
                tracing::info!("[ALERT] {}: {}", alert.title, alert.message);
            }
        }
        Ok(())
    }
}